package com.hn.shopadmin.service.impl;

import com.github.pagehelper.util.StringUtil;
import com.hn.shopadmin.dto.UserLoginDTO;
import com.hn.shopadmin.service.UserService;
import com.hn.shopadmin.compoent.AdminUserDetails;
import com.hn.shopadmin.dto.UserRegisterDTO;
import com.hn.shopadmin.util.JwtTokenUtil;
import com.hn.kiss.modules.sys.shopcommon.common.ParmException;
import com.hn.kiss.modules.sys.shopcommon.util.PinyinUtil;
import com.hn.kiss.modules.sys.shopcommon.util.RxUtil;
import com.hn.kiss.modules.sys.shopdb.entity.User;
import com.hn.kiss.modules.sys.shopdb.entity.UserExample;
import com.hn.kiss.modules.sys.shopdb.mapper.JurisdictionMapper;
import com.hn.kiss.modules.sys.shopdb.mapper.RoleJurisdictionMapper;
import com.hn.kiss.modules.sys.shopdb.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public  class UserServiceimpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private RoleJurisdictionMapper roleJurisdictionMapper;
    @Autowired
    private JurisdictionMapper jurisdictionMapper;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public User getUserByUserName(String username) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andEmallEqualTo(username);
        userExample.or().andPhoneEqualTo(username);
        userExample.or().andIdnoEqualTo(username);

        List<User> users = userMapper.selectByExample(userExample);
        if (users != null && users.size() > 0) {
            return users.get(0);
        }
        return null;
    }

    @Override
    public int insert(User user) {
        user.setId(RxUtil.getUUID());
        //加密密码
        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        //用户状态
        user.setState(1);
        //设置姓名简拼/拼音
        if(StringUtil.isNotEmpty(user.getName())){
            user.setPinyin(PinyinUtil.converterToFirstSpell(user.getName()));
            user.setPy(PinyinUtil.converterToSpell(user.getName()));
        }
        return userMapper.insert(user);
    }

    @Override
    public User getById(String id) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andIdEqualTo(id);

        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public int update(User user) {
        //加密密码
        if (StringUtil.isNotEmpty(user.getPassword())){
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }

        //设置姓名简拼/拼音
        if(StringUtil.isNotEmpty(user.getName())){
            user.setPinyin(PinyinUtil.converterToFirstSpell(user.getName()));
            user.setPy(PinyinUtil.converterToSpell(user.getName()));
        }
        user.setModifyDate(new Date());
        return userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public UserLoginDTO login(String username, String password) {
        System.out.println(username);
        //通过账号或用户信息
        AdminUserDetails userDetails = (AdminUserDetails) userDetailsService.loadUserByUsername(username);
        //校验密码
        if(!passwordEncoder.matches(password,userDetails.getPassword())){
            throw new BadCredentialsException("密码不正确");
        }
        User user = userDetails.getUser();
        //设置Authentication
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);

        //返回信息
        UserLoginDTO loginDTO = new UserLoginDTO();
        loginDTO.convertFor(user);
        loginDTO.setToken(token);

        return loginDTO;
    }

    @Override
    public int userRegister(UserRegisterDTO userRegisterDTO) throws ParmException {
        //校验手机号/身份证号/邮箱是否正确
        boolean b = valedatorUser(userRegisterDTO.getPhone(), userRegisterDTO.getIdno(), userRegisterDTO.getEmall());
        if (b){
            User user = userRegisterDTO.convertToUser();
            user.setRole("user");
            return insert(user);
        }
        throw new ParmException("账号已存在");
    }

    @Override
    public int shopRegister(UserRegisterDTO userRegisterDTO) throws ParmException {
        //校验手机号/身份证号/邮箱是否正确
        boolean b = valedatorUser(userRegisterDTO.getPhone(), userRegisterDTO.getIdno(), userRegisterDTO.getEmall());

        if (b){
            User user = userRegisterDTO.convertToUser();
            user.setRole("shopowner");
            return insert(user);
        }
        throw new ParmException("账号已存在");
    }

    @Override
    public int register(UserRegisterDTO userRegisterDTO, String role) throws ParmException {
        //校验手机号/身份证号/邮箱是否正确
        boolean b = valedatorUser(userRegisterDTO.getPhone(), userRegisterDTO.getIdno(), userRegisterDTO.getEmall());

        if (b){
            User user = userRegisterDTO.convertToUser();
            user.setRole(role);
            return insert(user);
        }
        throw new ParmException("账号已存在");
    }

    @Override
    public boolean valedatorUser(String phone, String idno, String emal) throws ParmException{
        if (StringUtil.isEmpty(phone) && StringUtil.isEmpty(idno) && StringUtil.isEmpty(emal)){
            throw new ParmException("手机号/身份证号/邮件不可同时为空");
        }

        User userByUserName = null;
        if (StringUtil.isNotEmpty(phone)){
            userByUserName = getUserByUserName(phone);
            if(userByUserName != null){
                throw new  ParmException("手机号已被注册");
            }
        }
        if (StringUtil.isNotEmpty(idno)){
            userByUserName = getUserByUserName(idno);
            if(userByUserName != null){
                throw new  ParmException("身份证号已被注册");
            }
        }
        if (StringUtil.isNotEmpty(emal)){
            userByUserName = getUserByUserName(emal);
            if(userByUserName != null){
                throw new  ParmException("邮箱已被注册");
            }
        }
        return true;

    }

    @Override
    public boolean valedatorPassword(String id, String password) {
        User user = getById(id);
        String encodePassword = passwordEncoder.encode(password);
        if (!passwordEncoder.matches(encodePassword, user.getPassword())){
            return true;
        }
        return false;

    }

    /*@Override
    public List<RoleJursdictionDTO> listRoleJursdiction() {
        List<Jurisdiction> jurisdictions = jurisdictionMapper.selectByExample(new JurisdictionExample());

        ArrayList<RoleJursdictionDTO> roleJursdictionDTOS = new ArrayList<RoleJursdictionDTO>();

        jurisdictions.forEach(jurisdiction -> {
            //查询权限对应的角色列表
            RoleJurisdictionExample roleJurisdictionExample = new RoleJurisdictionExample();
            roleJurisdictionExample.createCriteria().andJurisdictionIdEqualTo(jurisdiction.getId());
            List<RoleJurisdiction> roleJurisdictions = roleJurisdictionMapper.selectByExample(roleJurisdictionExample);

            //对应权限权限列表不为空,拼接权限url和角色对应关系
            if (roleJurisdictions != null && roleJurisdictions.size() > 0) {
                //获取角色code列表
                List<String> roles = roleJurisdictions.stream()
                        .map(roleJurisdiction -> roleJurisdiction.getRoleCode())
                        .collect(Collectors.toList());

                //拼接
                RoleJursdictionDTO roleJursdictionDTO = new RoleJursdictionDTO();
                roleJursdictionDTO.setJursdictionUrl(jurisdiction.getUrl());
                roleJursdictionDTO.setRoles(roles);
                roleJursdictionDTOS.add(roleJursdictionDTO);
            }
        });
        return roleJursdictionDTOS;
    }*/
}
